import { BaseEntity } from './BaseEntity';
import { quality } from '../../shared/face/enums';

/**
 * 装备实体类
 */
export class Equipment extends BaseEntity {
    /** 装备名称 */
    public name: string;
    
    /** 装备描述 */
    public description: string;
    
    /** 装备品质 */
    public quality: quality;
    
    /** 装备图标 */
    public icon: string;
    
    /** 装备表情符号 */
    public emoji: string;
    
    /** 装备位置类型 */
    public slotType: EquipmentSlot;
    
    /** 装备体系 */
    public system: string;
    
    /** 装备类型 */
    public type: string;
    
    /** 职业要求 */
    public jobRequirement: string;
    
    /** 等级要求 */
    public levelRequirement: number;
    
    /** 强化等级 */
    public enhanceLevel: number;
    
    /** 最大强化等级 */
    public maxEnhanceLevel: number;
    
    /** 装备属性 */
    public attributes: EquipmentAttribute[];
    
    /** 装备技能 */
    public skills: EquipmentSkill[];
    
    /** 装备来源 */
    public source: string;
    
    /** 创建者ID */
    public creatorId: string;
    
    /** 装备耐久度 */
    public durability: number;
    
    /** 最大耐久度 */
    public maxDurability: number;
    
    /** 是否已绑定 */
    public isBound: boolean;
    
    /** 套装ID */
    public setId?: string;
    
    /** 套装名称 */
    public setName?: string;
    
    /** 装备数据 */
    public data: EquipmentData;

    constructor(id?: string) {
        super(id);
        
        this.name = '';
        this.description = '';
        this.quality = (quality as any).白色;
        this.icon = '';
        this.emoji = '';
        this.slotType = EquipmentSlot.WEAPON;
        this.system = '';
        this.type = '';
        this.jobRequirement = '';
        this.levelRequirement = 1;
        this.enhanceLevel = 0;
        this.maxEnhanceLevel = 15;
        this.attributes = [];
        this.skills = [];
        this.source = '';
        this.creatorId = '';
        this.durability = 100;
        this.maxDurability = 100;
        this.isBound = false;
        this.data = {};
    }

    /**
     * 创建装备
     */
    public static create(config: EquipmentCreateConfig): Equipment {
        const equipment = new Equipment(config.id);
        
        equipment.name = config.name;
        equipment.description = config.description || '';
        equipment.quality = config.quality || (quality as any).白色;
        equipment.icon = config.icon || '';
        equipment.emoji = config.emoji || '';
        equipment.slotType = config.slotType || EquipmentSlot.WEAPON;
        equipment.system = config.system || '';
        equipment.type = config.type || '';
        equipment.jobRequirement = config.jobRequirement || '';
        equipment.levelRequirement = config.levelRequirement || 1;
        equipment.enhanceLevel = config.enhanceLevel || 0;
        equipment.maxEnhanceLevel = config.maxEnhanceLevel || 15;
        equipment.attributes = config.attributes || [];
        equipment.skills = config.skills || [];
        equipment.source = config.source || '';
        equipment.creatorId = config.creatorId || '';
        equipment.durability = config.durability || 100;
        equipment.maxDurability = config.maxDurability || 100;
        equipment.isBound = config.isBound || false;
        equipment.setId = config.setId;
        equipment.setName = config.setName;
        equipment.data = config.data || {};
        
        return equipment;
    }

    /**
     * 强化装备
     */
    public enhance(): EnhanceResult {
        if (this.enhanceLevel >= this.maxEnhanceLevel) {
            return {
                success: false,
                message: '装备已达到最大强化等级',
                newLevel: this.enhanceLevel
            };
        }

        // 强化成功率随等级递减
        const successRate = Math.max(0.3, 1 - (this.enhanceLevel * 0.1));
        const isSuccess = Math.random() < successRate;

        if (!isSuccess) {
            return {
                success: false,
                message: '强化失败',
                newLevel: this.enhanceLevel
            };
        }

        this.enhanceLevel += 1;
        
        // 强化后提升属性
        this.enhanceAttributes();
        
        this.updateEntity();

        return {
            success: true,
            message: `装备强化成功，当前强化等级：+${this.enhanceLevel}`,
            newLevel: this.enhanceLevel
        };
    }

    /**
     * 强化属性提升
     */
    private enhanceAttributes(): void {
        this.attributes.forEach(attr => {
            const enhancement = Math.floor(attr.baseValue * 0.1);
            attr.value = attr.baseValue + (enhancement * this.enhanceLevel);
        });
    }

    /**
     * 修理装备
     */
    public repair(amount?: number): RepairResult {
        if (this.durability >= this.maxDurability) {
            return {
                success: false,
                message: '装备不需要修理',
                repairedAmount: 0,
                newDurability: this.durability
            };
        }

        const repairAmount = amount || (this.maxDurability - this.durability);
        const actualRepair = Math.min(repairAmount, this.maxDurability - this.durability);
        
        this.durability += actualRepair;
        this.updateEntity();

        return {
            success: true,
            message: `装备修理完成，恢复耐久度 ${actualRepair}`,
            repairedAmount: actualRepair,
            newDurability: this.durability
        };
    }

    /**
     * 损坏装备
     */
    public damage(amount: number): void {
        this.durability = Math.max(0, this.durability - amount);
        this.updateEntity();
    }

    /**
     * 绑定装备
     */
    public bind(): void {
        this.isBound = true;
        this.updateEntity();
    }

    /**
     * 检查是否可以装备
     */
    public canEquip(playerLevel: number, playerJob: string): EquipCheckResult {
        const reasons: string[] = [];

        if (playerLevel < this.levelRequirement) {
            reasons.push(`需要等级 ${this.levelRequirement}`);
        }

        if (this.jobRequirement && playerJob !== this.jobRequirement) {
            reasons.push(`需要职业：${this.jobRequirement}`);
        }

        if (this.durability <= 0) {
            reasons.push('装备已损坏，需要修理');
        }

        return {
            canEquip: reasons.length === 0,
            reasons
        };
    }

    /**
     * 获取总属性值
     */
    public getTotalAttributes(): Record<string, number> {
        const totalAttributes: Record<string, number> = {};
        
        this.attributes.forEach(attr => {
            totalAttributes[attr.key] = (totalAttributes[attr.key] || 0) + attr.value;
        });

        return totalAttributes;
    }

    /**
     * 获取装备评分
     */
    public getEquipmentScore(): number {
        let score = 0;
        
        // 基础品质分数
        score += this.quality * 100;
        
        // 强化等级分数
        score += this.enhanceLevel * 50;
        
        // 属性分数
        this.attributes.forEach(attr => {
            score += attr.value * 2;
        });
        
        // 技能分数
        score += this.skills.length * 100;
        
        // 耐久度分数
        score += (this.durability / this.maxDurability) * 50;

        return Math.round(score);
    }

    /**
     * 获取品质名称
     */
    public getQualityName(): string {
        const qualityNames = {
            [(quality as any).白色]: '普通',
            [(quality as any).绿色]: '优秀',
            [(quality as any).蓝色]: '精良',
            [(quality as any).紫色]: '史诗',
            [(quality as any).橙色]: '传说',
            [(quality as any).红色]: '神话'
        };
        return qualityNames[this.quality] || '未知';
    }

    /**
     * 获取完整名称（包含强化等级）
     */
    public getFullName(): string {
        const enhancePrefix = this.enhanceLevel > 0 ? `+${this.enhanceLevel} ` : '';
        return `${enhancePrefix}${this.name}`;
    }

    /**
     * 检查是否为套装装备
     */
    public isSetEquipment(): boolean {
        return !!this.setId;
    }

    /**
     * 验证装备数据
     */
    public validate(): any {
        const result = super.validate();

        if (!this.name || this.name.trim().length === 0) {
            result.errors.push({ field: 'name', message: '装备名称不能为空' });
        }

        if (this.levelRequirement < 1) {
            result.errors.push({ field: 'levelRequirement', message: '等级要求必须大于0' });
        }

        if (this.enhanceLevel < 0 || this.enhanceLevel > this.maxEnhanceLevel) {
            result.errors.push({ field: 'enhanceLevel', message: `强化等级必须在0-${this.maxEnhanceLevel}之间` });
        }

        if (this.durability < 0 || this.durability > this.maxDurability) {
            result.errors.push({ field: 'durability', message: '耐久度无效' });
        }

        result.isValid = result.errors.length === 0;
        return result;
    }
}

/**
 * 装备槽位枚举
 */
export enum EquipmentSlot {
    WEAPON = 'weapon',        // 武器
    HELMET = 'helmet',        // 头盔
    ARMOR = 'armor',          // 护甲
    PANTS = 'pants',          // 裤子
    SHOES = 'shoes',          // 鞋子
    ACCESSORY = 'accessory',  // 饰品
}

/**
 * 装备属性接口
 */
export interface EquipmentAttribute {
    key: string;         // 属性键
    value: number;       // 当前值
    baseValue: number;   // 基础值
    type: AttributeType; // 属性类型
}

/**
 * 属性类型枚举
 */
export enum AttributeType {
    FIXED = 'fixed',        // 固定值
    PERCENTAGE = 'percentage' // 百分比
}

/**
 * 装备技能接口
 */
export interface EquipmentSkill {
    skillId: string;     // 技能ID
    name: string;        // 技能名称
    level: number;       // 技能等级
    triggerRate: number; // 触发概率
    description: string; // 技能描述
}

/**
 * 装备数据接口
 */
export interface EquipmentData {
    [key: string]: any;
}

/**
 * 装备创建配置接口
 */
export interface EquipmentCreateConfig {
    id?: string;
    name: string;
    description?: string;
    quality?: quality;
    icon?: string;
    emoji?: string;
    slotType?: EquipmentSlot;
    system?: string;
    type?: string;
    jobRequirement?: string;
    levelRequirement?: number;
    enhanceLevel?: number;
    maxEnhanceLevel?: number;
    attributes?: EquipmentAttribute[];
    skills?: EquipmentSkill[];
    source?: string;
    creatorId?: string;
    durability?: number;
    maxDurability?: number;
    isBound?: boolean;
    setId?: string;
    setName?: string;
    data?: EquipmentData;
}

/**
 * 强化结果接口
 */
export interface EnhanceResult {
    success: boolean;
    message: string;
    newLevel: number;
}

/**
 * 修理结果接口
 */
export interface RepairResult {
    success: boolean;
    message: string;
    repairedAmount: number;
    newDurability: number;
}

/**
 * 装备检查结果接口
 */
export interface EquipCheckResult {
    canEquip: boolean;
    reasons: string[];
}
